package org.supreme.basic.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.supreme.basic.defaut.Throw;
import org.supreme.basic.dtovo.Smscode;
import org.supreme.basic.dtovo.loginDto;
import org.supreme.basic.dtovo.wechatbangd;
import org.supreme.basic.excetion.GlobExcetionEnum;
import org.supreme.basic.excetion.GlobalExcetion;
import org.supreme.basic.result.JSONResult;
import org.supreme.basic.service.ILoginService;
import org.supreme.basic.util.HttpClientUtils;
import org.supreme.basic.util.MD5Utils;
import org.supreme.basic.util.StrUtils;
import org.supreme.user.domain.Logininfo;
import org.supreme.user.domain.User;
import org.supreme.user.mapper.LogininfoMapper;
import org.supreme.user.mapper.UserMapper;
import org.supreme.user.mapper.WxuserMapper;
import  org.supreme.user.domain.Wxuser;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public JSONResult login(loginDto dto) {
        //查询当前的用户是否注册
       Logininfo logininfo= logininfoMapper.selectLoginUsername(dto.getUsername(),dto.getType());
       if (logininfo==null){
           throw  new GlobalExcetion(GlobExcetionEnum.COMMON_USERNAME);
       }
       //判断当前的密码是否正确
        String password = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        System.out.println(password);
        if (!password.equals(logininfo.getPassword())){
            throw new GlobalExcetion(GlobExcetionEnum.COMMON_PASSWORD);
        }
        //将数据放到Redis中间，返回给前端
        HashMap<String, Object> Map = setTokenLongininfo(logininfo);
        return JSONResult.success(Map);
    }



    /**
     * 微信扫码登录
     * @param map
     * @return
     */
    @Override
    public JSONResult wechat(Map<String, String> map) {
        //判断前端传入的参数是否为空
        if(map==null){
            throw new GlobalExcetion(GlobExcetionEnum.COMMON_IS_FALLBACK);
        }
        //从map中间获取code的值
        String code = map.get("code");
        if (code==null){
            throw  new GlobalExcetion(GlobExcetionEnum.COMMON_CODE);

        }
        //拼接url地址
        String replace = Throw.GET_TOKEN.replace("APPID", Throw.APPID).replace("SECRET", Throw.SECRET)
                .replace("CODE",code);
        //发送请求获取token
        String token = HttpClientUtils.httpGet(replace);
        //把结果返回值转成json对象
        JSONObject object = JSONObject.parseObject(token);
        String access_token = object.getString("access_token");
        String openid = object.getString("openid");
        System.out.println(openid);
        //去数据库查询是否存在
      Wxuser wxuser= wxuserMapper.selectOpenId(openid);
        //判断当前的用户是否有数据
        if (wxuser!=null){
            User user=userMapper.selectUserId(wxuser.getUserId());
            Long logininfoId = user.getLogininfoId();
            Logininfo logininfo=logininfoMapper.selectLogininId(logininfoId);
            //将值存入到Redis中间。返回给前端,key是UUID值是logininfo
            HashMap<String, Object> Map = setTokenLongininfo(logininfo);
            return JSONResult.success(Map);
        }
        //如果不存在就返回token与openid
        String url = "?access_token="+access_token+"&openid="+openid;
        return JSONResult.issuccess(url,"binder");
    }

    /**
     * 微信绑定页面业务实现
     * @param we
     * @return
     */

    @Override
    @Transactional
    public JSONResult wechatbangd(wechatbangd we) {
        //判断两次密码是不是一样的
        if (!we.getPassword().equals(we.getConfirmPassword())){
            throw  new GlobalExcetion(GlobExcetionEnum.COMMON_USERCODE_DTO);
        }
        //数据库里面查询有没有改用户是否绑定
        Logininfo log = logininfoMapper.selectLogininPhone(we.getUsername());
        if (log!=null){
            throw  new GlobalExcetion(GlobExcetionEnum.COMMON_USER);
        }
        //如果是为空，证明改用户没有绑定过，重新绑定，并且绑定3张表
        //先绑定user表
        //添加logininfo表
        setLOGINFO(we);
        //添加user表
        setUser(we);
        //添加wxuser表
        setWxuser(we);
        //将数据保存到Redis中间，返回给前端
        Logininfo logininfo=logininfoMapper.selectLogininPhone(we.getUsername());
        HashMap<String, Object> Map = setTokenLongininfo(logininfo);
        return JSONResult.success(Map);
    }
    //添加user表的方法
    private void setUser(wechatbangd we) {
        User user1 = new User();
        user1.setUsername(we.getUsername());
        user1.setPhone(we.getUsername());
        String complexRandomString = StrUtils.getComplexRandomString(32);
        user1.setSalt(complexRandomString);
        String s = MD5Utils.encrypByMd5(complexRandomString + we.getPassword());
        user1.setPassword(s);
        user1.setState(1);
        user1.setAge(23);
        user1.setCreatetime(new Date());
        Logininfo Logininfo = logininfoMapper.selectLogininPhone(we.getUsername());
        Long id = Logininfo.getId();
        user1.setLogininfoId(id);
        userMapper.insert(user1);
    }
    //添加logininfo的表
    private void setLOGINFO(wechatbangd we) {
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(we.getUsername());
        logininfo.setPhone(we.getUsername());
        //获取盐值
        String complexRandomString = StrUtils.getComplexRandomString(32);
        logininfo.setSalt(complexRandomString);
        //设置密码
        String s = MD5Utils.encrypByMd5(complexRandomString+ we.getPassword());
        logininfo.setPassword(s);
        logininfo.setType(1);
        logininfo.setDisable(1);
        logininfoMapper.insert(logininfo);
    }
    //添加wxuser的表
    private void setWxuser(wechatbangd we) {
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(we.getOpenId());
        wxuser.setNickname(we.getUsername());
        wxuser.setAddress("源码黄家会所");
        wxuser.setSex(1);
        wxuser.setHeadimgurl(we.getToken());
        wxuser.setUnionid(we.getToken());
        User user = userMapper.selectPhone(we.getUsername());
        wxuser.setUserId(user.getId());
        wxuserMapper.insert(wxuser);
    }
    //给前端返回token与longininfo，要存入到localstorage中间
    private HashMap<String, Object> setTokenLongininfo(Logininfo logininfo) {
        //将值存入到Redis中间。返回给前端,key是UUID值是logininfo
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回给前端
        HashMap<String, Object> Map = new HashMap<>();
        Map.put("token",token);
        logininfo.setPassword(null);
        logininfo.setDisable(null);
        logininfo.setSalt(null);
        logininfo.setType(null);
        Map.put("logininfo", logininfo);
        return Map;
    }
}
